<?php

namespace App\Http\Controllers\Manage;

use App\Rule;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Article;
use App\Category;
use Illuminate\Support\Facades\Storage;
use Validator;
use Illuminate\Support\Facades\Redirect;

class ArticleController extends Controller
{
    public $table_id = 1;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $categorys = Category::all();
        $articles = Article::orderBy('rank', 'desc')->orderBy('id','desc')->paginate(10);
        return view('manage/article/index', compact('categorys', 'articles'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $categorys = Category::all();
        $articles = Article::all();
        return view('manage/article/create', compact('articles', 'categorys'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $savePath  = null;

        $input = $request->only('category', 'title', 'content', 'rank');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'content' => 'required',
            'rank' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'content' => '内容',
            'rank' => '权重'
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            // 查找重复
            if(Article::whereTitle($input['title'])->first()) {
                return redirect()->back()->withInput()->withErrors('文章标题已经存在');
            }
            else {
                if($request->hasFile('file')) {
                    $file = $request->file('file');
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传文件有误！');
                    }
                    $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                    $savePath = 'files/' . $newFileName;
                    $bytes = Storage::put(
                        $savePath,
                        file_get_contents($file->getRealPath())
                    );
                    if(!Storage::exists($savePath)) {
                        return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                    }
                }

                if(Article::insert([
                    'category' => $request->input('category'),
                    'title' => $request->input('title'),
                    'author' => $request->input('author'),
                    'keyword' => $request->input('keyword'),
                    'description' => $request->input('description'),
                    'content' => $request->input('content'),
                    'file' => $savePath,
                    'rank' => $request->input('rank'),
                    'status' => $request->input('rank')
                ])) {
                    return Redirect::to("manage/article");
                }
                else  {
                    return redirect()->back()->withInput()->withErrors('添加失败');
                }
            }
        }
        return redirect("manage/article/index");

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $status = Article::whereId($id)->pluck('status');
        $status = $status[0];
        if($status == 0) {
            if(Article::whereId($id)->update(['status' => 1])) {
                return redirect()->back()->withInput()->withSuccess('文章ID:'.$id.' 状态已启用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('文章ID:'.$id.' 状态启用失败');
            }
        }
        else {
            if(Article::whereId($id)->update(['status' => 0])) {
                return redirect()->back()->withInput()->withSuccess('文章ID:'.$id.' 状态已禁用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('文章ID:'.$id.' 状态禁用失败');
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $categorys = Category::all();
        $articles = Article::whereId($id)->first();
        return view('manage/article/edit', compact('categorys', 'articles'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $savePath  = null;

        $input = $request->only('category', 'title', 'content', 'rank');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'content' => 'required',
            'rank' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'content' => '内容',
            'rank' => '权重'
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            $savePath = null;
            if($request->hasFile('file')) {
                $file = $request->file('file');
                if(!$file->isValid()) {
                    return redirect()->back()->withInput()->withErrors('上传文件有误！');
                }
                $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                $savePath = 'files/' . $newFileName;
                $bytes = Storage::put(
                    $savePath,
                    file_get_contents($file->getRealPath())
                );
                if(!Storage::exists($savePath)) {
                    return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                }
            }
            else {
                $savePath = Article::whereId($id)->pluck('file')[0];
            }
            if(Article::where('id', $id)->update([
                'category' => $request->input('category'),
                'title' => $request->input('title'),
                'author' => $request->input('author'),
                'keyword' => $request->input('keyword'),
                'description' => $request->input('description'),
                'content' => $request->input('content'),
                'file' => $savePath,
                'rank' => $request->input('rank'),
                'status' => $request->input('status')
            ])) {
                return Redirect::to("manage/article");
            }
            else  {
                return redirect()->back()->withInput()->withErrors('更新失败');
            }

        }
        return redirect("manage/article/index");

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return array|null
     */
    public function destroy($id)
    {
        $callback = null;
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }

        $file = Article::whereId($id)->pluck("file");
        if(Article::destroy($id)) {
            if($file) {
                if(Storage::delete($file[0])) {
                    $callback = [
                        'code' => 100,
                        'msg' => '删除成功！'
                    ];
                }
                else {
                    $callback = [
                        'code' => 100,
                        'msg' => '文章删除成功，图片删除失败！图片地址' . $file
                    ];
                }
            }
            else {
                $callback = [
                    'code' => 100,
                    'msg' => '删除成功！'
                ];
            }
        }
        else {
            $callback = [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
        return $callback;
    }

//    /**
//     * @param $id
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function seo($id)
//    {
//        #获取对应案例seo信息
//        $seo = Article::where('id',$id)->select('id','title','seo_title','seo_keyword','seo_description')->first();
//        return view('manage.case.seo',compact('seo'));
//    }
//
//    public function setSeo()
//    {
//        $id = Input::get('id');
//        $data['title'] = Input::get('title');//标题
//        $data['keyword'] = Input::get('keyword');//关键字
//        $data['description'] = Input::get('description');//描述
//        #获取对应案例信息
//        $case = ClientCase::where('id',$id)->first()->toArray();
//        foreach ($case as $k=>$v){
//            $data['title'] = str_replace("{".$k."}",$v,$data['title']);
//            $data['keyword'] = str_replace("{".$k."}",$v,$data['keyword']);
//            $data['description'] = str_replace("{".$k."}",$v,$data['description']);
//        }
//
////        $data['title'] = str_replace("{".array_keys($case,$case['title'])."}",$case['title'],$title);
//
//        if(ClientCase::where('id',$id)->update($data)){
//            return [
//                'code'=>$data,
//                'msg'=>'修改成功！'
//            ];
//        }else{
//            return [
//                'code'=>101,
//                'msg'=>'修改失败！'
//            ];
//        }
//    }

}
